<!--  -->
<template>
  <div>
    <el-dialog v-if="dialogFormVisible" :title="'线段“'+xdmc+'”下属停电用户'" :before-close="handleClose" :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="1200px" top="8vh" v-dialogDrag>
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <el-tab-pane :label="yxyhLabel" name="yxyh">
          <div class="tab-pane-item" v-if="activeTab === 'yxyh'">
            <div class="tab-pane-btn">
              <el-button size="mini" @click="handleDeleteYxyh">删除</el-button>
              <el-button size="mini" @click="handlleUpdateYxyh">修改</el-button>

              <el-button type="primary" size="mini" @click="cccEvent('show', yxxdyxTable, 'yxyh')">列配置</el-button>
            </div>
            <div class="tab-pane-table">
              <el-table
                ref="yxxdTable"
                :data="addedList"
                :header-cell-style="{'color':'#858585','font-weight':'400','background-color':'#fcfcfc'}"
                highlight-current-row
                height="400"
                border
                :cell-style="yhCellStyle"
                @selection-change="handleYjYhSelectionChange"
                v-loading="dialog_yxYHlistLoading"
              >
                <el-table-column fixed="left" align="center" type="selection" width="50"></el-table-column>
                <el-table-column label="序号" type="index" width="50" align="center" fixed="left"></el-table-column>
                <template v-for="col in yhyxColumnData">
                  <el-table-column
                    :show-overflow-tooltip="true"
                    :key="col.id"
                    :prop="col.field"
                    :label="col.title"
                    :min-width="col.minWidth"
                    :align="col.align"
                    :header-align="col.align"
                    :sortable="col.sortable"
                    :formatter="col.formatter"
                    :fixed="col.fixed"
                  ></el-table-column>
                </template>
              </el-table>
              <el-pagination
                class="pagination-container"
                @size-change="dialog_YHhandleSizeChange"
                @current-change="dialog_YHhandleCurrentChange"
                :current-page.sync="yxListQuery.current"
                :page-size="yxListQuery.size"
                :page-sizes="[5, 10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="addedTotal"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="wxyhLabel" name="wxyh">
          <div class="tab-pane-item" v-if="activeTab === 'wxyh'">
            <div class="tab-pane-btn">
              <el-button size="mini" @click="handleAddwxyh">添加</el-button>
              <el-button type="primary" size="mini" @click="cccEvent('show', yxxdwtTable, 'wxyh')">列配置</el-button>
            </div>
            <div class="tab-pane-table">
              <el-table
                ref="wxyhTable"
                :data="wx_list"
                :header-cell-style="{'color':'#858585','font-weight':'400','background-color':'#fcfcfc'}"
                highlight-current-row
                height="400"
                border
                v-loading="dialog_wxYHlistLoading"
                :cell-style="yhCellStyle"
                @selection-change="handleWxYhSelectionChange"
              >
                <el-table-column fixed="left" align="center" type="selection" width="50"></el-table-column>
                <el-table-column label="序号" type="index" width="50" align="center" fixed="left"></el-table-column>
                <template v-for="col in wxthColumnData">
                  <el-table-column
                    :show-overflow-tooltip="true"
                    :key="col.id"
                    :prop="col.field"
                    :label="col.title"
                    :min-width="col.minWidth"
                    :align="col.align"
                    :header-align="col.align"
                    :sortable="col.sortable"
                    :formatter="col.formatter"
                    :fixed="col.fixed"
                  ></el-table-column>
                </template>
              </el-table>
              <el-pagination
                class="pagination-container"
                @size-change="dialog_wxYHhandleSizeChange"
                @current-change="dialog_wxYHhandleCurrentChange"
                :current-page.sync="wxListQuery.current"
                :page-size="wxListQuery.size"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="wxTotal"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        
        <el-button @click="handleClose" size="mini">关 闭</el-button>
        <el-button type="primary" @click="save" size="mini" :disabled="tempControl == '0'" :loading="btnloading">确 定</el-button>
      </div>
    </el-dialog>

    <yxzyYhUpdate :updateYhList="updateYhList" @updateYhCallData="updateYhCallData"></yxzyYhUpdate>

    <ccc ref="ccc"></ccc>
  </div>
</template>

<script>
import ccc from "@/dialogCommom/ccc";
import yxzyYhUpdate from "./yxzyYhUpdate"; //修改用户弹窗
import { getZczyYhTable } from "@/api/sjwh/zczy.js";
import { getYxzyYhListTemp, saveYxzyYhTemp, deleteYxzyYhTemp, commitYxzyYhTemp } from '@/api/sjwh/yxzyyh.js';
export default {
  data() {
    return {
      TOKEN: 0,
      sjId: "", //表单事件id
      tempControl: "0", //当次操作标志，0：正式表/1：临时表
      dialogFormVisible: false, // 弹窗状态控制
      dialog_wxYHlistLoading: false, //未选用户loading
      dialog_yxYHlistLoading: false, //已选用户loading
      yxxdRow: [], //父级传过来的数据
      btnloading: false,
      xdmc: "线段一", //弹窗title
      czy: "", //操作员
      addedList: [],
      yxListQuery: {
        current: 1,
        size: 10,
      },
      addedTotal: 0,
      wxListQuery: {
        current: 1,
        size: 10,
      },
      wxlistQuery: {
        //用户查询条件
        current: 1,
        size: 10,
        dwbm: [], //单位编码
        sjqssj: "",
        sjzzsj: "",
        xdId: "", //线段ID
        neIds: [], //筛选用户
        // ascs: ["dwbm","yhbm"], //排序
      },
      wx_list: [], //未选择用户---从台账来
      wxTotal: 0, //未选用户的total
      yxxdyxTable: "yx_zytdyh", //运行用户配置列  ---已添加
      yhyxColumnData: [],
      yxxdwtTable: "zc_zyyhsj", //运行用户配置列  ---未添加  台账
      wxthColumnData: [],

      activeTab: "",
      yxyhLabel: "已添加用户",
      wxyhLabel: "未添加用户",
      yxyhCheckList: [],
      wxyhChceckList: [],
      updateYhList: {
        //传给修改用户的字段
        TOKEN: 0,
        visibal: false,
        yhData: {},
        xdsj: {},
        czy: "",
      },
      getRowKeys(row) {
        return row.yhId;
      },
    };
  },

  props: {
    yhPardata: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },

  components: {
    ccc,
    yxzyYhUpdate
  },

  computed: {},

  watch: {
    yhPardata(newVal, oldVal) {
      
      this.TOKEN = newVal.TOKEN;
      this.sjId = newVal.sjId;
      this.tempControl = "0";
      this.dialogFormVisible = newVal.visibal;
      this.czy = newVal.czy;
      this.yxxdRow = newVal.xdRow;
      this.xdmc = newVal.xdRow[0].xdmc;
      this.activeTab = "yxyh";
      this.getYxZyyhTempList();
    },
  },

  created() {},

  mounted() {
    this.yxcccEvent("load", this.yxxdyxTable);
    this.wxcccEvent("load", this.yxxdwtTable);
  },

  beforeUpdate() {
    //解决列配置引发的滚动条问题
  },

  update() {},

  destroyed() {},

  methods: {
    /**获取运行用户（已选用户数据） */
    getYxZyyhTempList() {
      this.getYxZyyhLs();
    },

    /**获取临时表数据 */
    getYxZyyhLs() {
      this.dialog_yxYHlistLoading = true;
      let reqData = {
        sjId: this.sjId,
        xdId: this.yxxdRow[0].xdId,
        current: this.yxListQuery.current,
        size: this.yxListQuery.size,
        ascs: ["qssj desc,yhbm"],
        temp: this.tempControl,
      };
      
      getYxzyYhListTemp(reqData).then((res) => {
        if (res.code === 0) {
          this.addedList = res.data.records;
          this.addedTotal = res.data.total;
          if(this.addedTotal == 0){
            this.$message.warning("当前线段下无用户，保存后将自动删除！");
          }
          this.dialog_yxYHlistLoading = false;
        }else{
          this.dialog_yxYHlistLoading = false;
        }
      });
    },

    /**运行分页 */
    dialog_YHhandleSizeChange(val) {
      this.yxListQuery.size = val;
      this.yxListQuery.current = 1;
      this.getYxZyyhTempList();
    },
    /**运行分页 */
    dialog_YHhandleCurrentChange(val) {
      this.yxListQuery.current = val;
      this.getYxZyyhTempList();
    },

    /**当用户数据中有双电源用户的时候，该条用户数据标红 */
    yhCellStyle({ row, column, rowIndex, columnIndex }) {

      //当数据类型为待维护，或者为待审核的时候
      if (row.issdy == "1") {
        return "color: red;";
      }else {
        if (row.gylxm == "1" || row.gylxm == "2" || row.gylxm == "3") {
          return "color: #E6A23C;"
        }
      }
    },

    /**添加台账用户 */
    handleAddwxyh() {

      let wxyhChceckListDatas = JSON.parse(JSON.stringify(this.wxyhChceckList));
      if (wxyhChceckListDatas.length <= 0) {
        this.$message.warning("请至少选择一条用户数据操作！");
        return false;
      }

      this.$confirm("是否添加已选择的用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        center: false,
      })
        .then(() => {
          this.changeWxyh();
        })
        .catch(() => {});
    },

    /**台账用户 -> 运行用户 数据转化 */
    async changeWxyh() {
      let loading = this.$loading({
          lock: true,
          text: '操作中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        try {
          let reqData = {
        TOKEN: this.TOKEN,
        czy: this.czy,
        sjId: this.sjId,
        xdId: this.yxxdRow[0].xdId,
        zcyhList: this.wxyhChceckList,
        temp: this.tempControl,
      };
      let res = await saveYxzyYhTemp(reqData);
     
      if (res.code === 0 && res.data === true) {
        this.$message({
          message: "用户已添加！",
          type: "success",
        });
        loading.close()
        this.tempControl = "1";
        this.activeTab = "yxyh"; //跳转添加用户
        this.getYxZyyhTempList(); //跳转修改用户
      }else{
        loading.close()
        this.$message.error(res.message)
      }
        } catch (error) {
          loading.close()
        }
      
    },

    /**删除运行用户 */
    handleDeleteYxyh() {
      let deletDatas = JSON.parse(JSON.stringify(this.yxyhCheckList));
     
      if (deletDatas.length <= 0) {
        this.$message.warning("请选择一条用户数据操作！");
        return false;
      }

      this.$confirm("是否删除已选择的用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        center: false,
      })
        .then(() => {
          this.deleteBatchYxZytdxh();
        })
        .catch(() => {});
    },
    async deleteBatchYxZytdxh() {
      let loading;
      try {
        loading = this.$loading({
          lock: true,
          text: '操作中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let deletDatas = JSON.parse(JSON.stringify(this.yxyhCheckList));
      let ids = deletDatas.map((item) => {
        return item.id;
      });
      let reqData = {
        TOKEN: this.TOKEN,
        czy: this.czy,
        sjId: this.sjId,
        xdId: this.yxxdRow[0].xdId,
        ids: ids,
        temp: this.tempControl,
      };
     
      let res = await deleteYxzyYhTemp(reqData);
    
      if (res.code === 0 && res.data === true) {
        loading.close();
        this.$message.success("删除成功");
        this.tempControl = "1";
        this.getYxZyyhTempList();
      } else {
        loading.close();
        this.$message.error(res.message);
        return;
      }

      } catch (error) {
        loading.close();
      }
      
    },

    /**修改用户 */
    handlleUpdateYxyh() {
    
      let updateData = JSON.parse(JSON.stringify(this.yxyhCheckList));
      if (updateData.length <= 0 || updateData.length > 1) {
        this.$message.warning("请选择一条用户数据操作！");
        return false;
      }
      let yhList = updateData[0];
 
      let xdsj = {
        qssj: this.yxxdRow[0].qssj,
        zzsj: this.yxxdRow[0].zzsj,
      };
      // this.$refs.yxxdTable.toggleRowSelection(this.yxxdRow.selectedYhList[yhList]);
      this.updateYhList = JSON.parse(
        JSON.stringify({
          TOKEN: this.TOKEN,
          sjId: this.sjId,
          temp: this.tempControl,
          visibal: true,
          yhList: yhList,
          xdsj: xdsj,
          czy: this.czy,
        })
      );
    },

    /**修改用户回传事件 */
    updateYhCallData(val) {
      let yhPardata = val;

      if (yhPardata === true) {
        this.$message.success("修改成功！");
        this.tempControl = "1";
        this.getYxZyyhTempList();
      }
    },

    /**选择已添加的用户 */
    handleYjYhSelectionChange(val) {
      this.yxyhCheckList = val;

    },
    handleWxYhSelectionChange(val) {

      this.wxyhChceckList = val;
    },

    /**点击tab切换 */
    handleTabClick(tab, event) {
      if (tab.name === "wxyh") {
        this.getYhlist();
      } else {
        this.getYxZyyhTempList();
      }
    },
    /**获取用户数据 --- 台账 */
    getYhlist() {
      this.dialog_wxYHlistLoading = true;
      let xdId = this.yxxdRow[0].xdId;
      let reqData = {
        current: this.wxListQuery.current,
        size: this.wxListQuery.size,
        dwbm: [this.yxxdRow[0].zrbm], //单位编码
        sjqssj: this.yxxdRow[0].qssj,
        sjzzsj: this.yxxdRow[0].zzsj,
        xdId: [xdId], //线段ID
        sjId: this.sjId,
        tyzt: "1",
        temp: this.tempControl
      };
   
      getZczyYhTable(reqData)
        .then((res) => {
      
          if (res.code == 0) {
            this.wx_list = res.data.records;
            this.wxTotal = res.data.total;
            this.dialog_wxYHlistLoading = false;
          }
        })
        .catch((error) => {});
    },
    /**台账分页 */
    dialog_wxYHhandleSizeChange(val) {
      this.wxListQuery.size = val;
      this.wxListQuery.current = 1;
      this.getYhlist();
    },
    /**台账分页 */
    dialog_wxYHhandleCurrentChange(val) {
      this.wxListQuery.current = val;
      this.getYhlist();
    },

    /**保存 */
    async save() {
      
      try {
        let reqData = {
        TOKEN: this.TOKEN,
        czy: this.czy,
        sjId: this.sjId,
        xdId: this.yxxdRow[0].xdId,
        sfbc: "1",
      };
      this.btnloading = true;
      let res = await commitYxzyYhTemp(reqData);
 
      if (res.code === 0 && res.data) {
        this.btnloading = false;
        this.$message.success("操作成功");
        this.dialogFormVisible = false;
        this.tempControl = "0";
        this.$emit("handleAddYxyh", { bool: true });
      } else {
        this.btnloading = false;
        this.$message.error(res.message);
        return;
      }
      } catch (error) {
        this.btnloading = false;
      }
      
      // this.countYxxd();
    },
    /**取消 */
    async handleClose() {
      this.clearYhTableData()
      if (this.tempControl == "0") {
        let callData = {
          bool: true,
        };
        this.dialogFormVisible = false;
        this.$emit("handleAddYxyh", callData);
      } else if (this.tempControl == "1") {
        let reqData = {
          TOKEN: this.TOKEN,
          czy: this.czy,
          sjId: this.sjId,
          xdId: this.yxxdRow[0].xdId,
          sfbc: "0",
        };
       
        let res = await commitYxzyYhTemp(reqData);
      
        if (res.code === 0 && res.data === true) {
          this.dialogFormVisible = false;
          this.tempControl = "0";
          this.$emit("handleAddYxyh", { bool: true });
        } else {
          this.dialogFormVisible = false;
          this.tempControl = "0";
          this.$message.error('操作取消！');
          return;
        }
      }
    },
    clearYhTableData(){
      this.yxListQuery.current = 1;
      this.yxListQuery.size = 10;
      this.wxListQuery.current = 1;
      this.wxListQuery.size = 10;
    },

    yxcccEvent(method, table) {
      if (method === "show") {
        this.$refs.ccc.show(table);
      } else if (method === "load") {
        new Promise((resolve, reject) => {
          this.$nextTick(() => {
            resolve(this.$refs.ccc.load(table));
          });
        }).then((response) => {
          this.yhyxColumnData = response;
        });
      } else if (method === "export") {
        let vo = {
          tableCode: table,
          param: this.listQuery,
          url: "",
          method: "GET",
          fileName: "",
        };
        this.$refs.ccc.exportExcel(vo);
      }
    },
    wxcccEvent(method, table) {
      if (method === "show") {
        this.$refs.ccc.show(table);
      } else if (method === "load") {
        new Promise((resolve, reject) => {
          this.$nextTick(() => {
            resolve(this.$refs.ccc.load(table));
          });
        }).then((response) => {
          this.wxthColumnData = response;
        });
      } else if (method === "export") {
        let vo = {
          tableCode: table,
          param: this.listQuery,
          url: "",
          method: "GET",
          fileName: "",
        };
        this.$refs.ccc.exportExcel(vo);
      }
    },

    /**配置列  */

    cccEvent(method, table, type) {
      if (method === "show") {
        if (type === "yxyh") {
          this.$refs.ccc.show(this.yxxdyxTable, type);
        } else if (type === "wxyh") {
          this.$refs.ccc.show(this.yxxdwtTable, type);
        }
      } else if (method === "load") {
        new Promise((resolve, reject) => {
          this.$nextTick(() => {
            resolve(this.$refs.ccc.load(table));
          });
        }).then((response) => {
          if (type === "yxyh") {
            this.yxxdColumnData = response;
          } else if (type === "wxyh") {
            this.wxthColumnData = response;
          }
        });
      }
    },
  },
};
</script>
<style lang='scss' scoped>
.tab-pane-item {
  position: relative;
  width: 100%;
}
.tab-pane-btn {
  position: absolute;
  right: 0;
  top: -36px;
  z-index: 1000;
}
.tab-pane-table {
  width: 100%;
}
/deep/.el-tabs .el-tabs__content {
  overflow: visible;
}
/deep/.el-tabs--card > .el-tabs__header {
  margin-bottom: 0;
}
/deep/ .el-dialog__footer {
  padding: 5px 10px 5px;
}
.pagination-container {
  text-align: center;
}
</style>
